package com.xx.doublexchat.common.common.interceptor;

import cn.hutool.http.ContentType;
import com.xx.doublexchat.common.common.exception.HttpErrorEnum;
import com.xx.doublexchat.common.user.service.ILoginService;
import lombok.val;
import com.google.common.base.Charsets;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.Optional;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    public static final String HEADER_AUTHORIZATION = "Authorization";
    public static final String AUTHORIZATION_SCHEMA = "Bearer ";
    public static final String UID = "uid";

    @Autowired
    private ILoginService loginService;

    /**
     * 前置拦截器
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = getToken(request);
        Long uid = loginService.getValidUid(token);
        // 用户存在登录态，uid不为空
        if (Objects.nonNull(uid)) {
            request.setAttribute(UID, uid);
        } else {
            //用户未登录
            // 请求路径
            boolean isPublicURI = isPublicURI(request);
            if (!isPublicURI) {
                // 非通用方法 需要返回401
                HttpErrorEnum.ACCESS_DENIED.sendHttpError(response);
                return false;
            }
        }
        return true;
    }

    /**
     * 判断是否为public接口
     * @param request
     * @return
     */
    private static boolean isPublicURI(HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        String[] split = requestURI.split("/");
        boolean isPublicURI = split.length > 3 && "public".equals(split[3]);
        return isPublicURI;
    }

    /**
     * 获取token
     *
     * @param request
     * @return
     */
    private String getToken(HttpServletRequest request) {
        String header = request.getHeader(HEADER_AUTHORIZATION);
        return Optional.ofNullable(header)
                .filter(h -> h.startsWith(AUTHORIZATION_SCHEMA))
                .map(h -> h.replaceFirst(AUTHORIZATION_SCHEMA, ""))//用空替换掉协议方便解析token
                .orElse(null);
    }
}
